
from flask import Flask, jsonify
from flask_cors import CORS
import os
import click
import colorlog

import logging


from lina.settings import config


from lina.extensions import db, moment


def create_app(config_name=None):
    # 初始化app
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')

    app = Flask('lina')
    app.config.from_object(config[config_name])
    CORS(app=app, resources=r'/*')

    # 注册插件
    register_blueprints(app)
    register_extensions(app)
    register_commands(app)
    register_logging(app)
    register_errhandler(app)

    logging.getLogger('lina_console').info("app started...")

    return app


def register_extensions(app):
    # 加载扩展
    moment.init_app(app)
    db.init_app(app)


def register_blueprints(app):
    # 注册蓝图
    from lina.blueprints.admin import blueprint as admin_bp
    from lina.blueprints.mainpage import blueprint as mainpage_bp
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(mainpage_bp, url_prefix='/')


def register_logging(app):
    # 注册日志 - 控制台日志
    logger = logging.getLogger('lina_console')
    logger.setLevel(logging.DEBUG)
    hdr = logging.StreamHandler()
    # formatter = logging.Formatter(
    #     '%(asctime)s - %(name)s - [%(log_color)s%(levelname)s] - %(message)s')

    formatter = colorlog.ColoredFormatter(
        '%(asctime)s - %(name)s - %(log_color)s[%(levelname)s]%(reset)s - %(message)s')

    hdr.setFormatter(formatter)

    logger.addHandler(hdr)
    app.logger = logger

    # 还可以添加其他的日志
    #   文件日志
    #   邮件日志
    pass


def register_errhandler(app):
    @app.errorhandler(Exception)
    def error_handler(e):
        data = {
            "code": -1,
            "msg": str(e),
            "data": None
        }
        logging.getLogger('lina_console').error(str(e))
        return jsonify(data)


def register_commands(app):

    @app.cli.command("forge")
    def forge():
        from lina.fake import fake_phase, fake_case, fake_task, fake_tag, fake_comment

        click.echo('插入示例标签...')
        fake_tag()

        click.echo('插入阶段列表...')
        inserted_phase_ids = fake_phase()

        click.echo('插入案件列表...')
        inserted_case_ids = fake_case(inserted_phase_ids)

        click.echo('插入任务列表...')
        inserted_task_ids = fake_task(inserted_case_ids)

        click.echo('插入评论列表...')
        insert_comment_ids = fake_comment(inserted_case_ids)

        click.echo("forge......")
        pass
